<template>
	<v-layout type="main">
		<ul class="home-monitoring">
			<li class="cpu">
				<div class="txt">
					<p class="name">CPU</p>
					<p class="msg">
						剩余
						<span>{{ (cpuRes.limit - cpuRes.used).toFixed(1) }}</span>
						{{ cpuRes.unit }}
					</p>
				</div>
				<percentage :res="cpuRes" />
				<!-- <div class="monitoring-layer" @mouseover="monitoringOver('cpuRes')" @mouseout="monitoringOut('cpuRes')"></div> -->
			</li>
			<!-- <li class="vgpu">
        <p class="name">VGPU</p>
        <div></div>
      </li> -->
			<li class="ram">
				<div class="txt">
					<p class="name">内存</p>
					<p class="msg">
						剩余
						<span>{{ (memRes.limit - memRes.used).toFixed(1) }}</span>
						{{ memRes.unit }}
					</p>
				</div>
				<percentage :res="memRes" />
				<!-- <div class="monitoring-layer" @mouseover="monitoringOver('memRes')" @mouseout="monitoringOut('memRes')"></div> -->
			</li>

			<li class="gpu">
				<div class="txt">
					<p class="name">GPU</p>
					<p class="msg">
						剩余
						<span>{{ (gpuRes.limit - gpuRes.used).toFixed(1) }}</span>
						{{ gpuRes.unit }}
					</p>
				</div>
				<percentage v-if="VUE_APP_USER === 'wanjie'" :res="gpuRes" :gpu-left="gpuLeft" />
				<percentage v-else :res="gpuRes" />
				<!-- <div class="monitoring-layer" @mouseover="monitoringOver('gpuRes')" @mouseout="monitoringOut('gpuRes')"></div> -->
			</li>

			<li class="ram">
				<div class="txt">
					<p class="name">硬盘</p>
					<p class="msg">
						剩余
						<span>{{ (diskRes.limit - diskRes.used).toFixed(1) }}</span>
						{{ diskRes.unit }}
					</p>
				</div>
				<percentage :res="diskRes" />
				<!-- <div class="monitoring-layer" @mouseover="monitoringOver('memRes')" @mouseout="monitoringOut('memRes')"></div> -->
			</li>
		</ul>

		<!-- <el-radio-group v-model="showThisActive" size="medium" @change="checkActicve(showThisActive)" class="nav-alike">
      <el-radio-button :label="0">
        <span class="nav-alike-item">模型开发</span>
      </el-radio-button>
      <el-radio-button :label="1">
        <span class="nav-alike-item">模型训练</span>
      </el-radio-button>
      <el-radio-button :label="2">
        <span class="nav-alike-item" v-if="!$isReinforce">模型部署</span>
        <span class="nav-alike-item" v-if="$isReinforce">模型测试</span>
      </el-radio-button>
    </el-radio-group> -->

		<div class="alike-lis-header">
			<div class="lis-header-left">
				<div style="font-size: 18px;">任务</div>
			</div>

			<div class="lis-header-right">
				<el-select size="mini" placeholder="请选择" v-model="showThisActive" @change="getData">
					<el-option label="模型开发" value="0"></el-option>
					<el-option label="模型训练" value="1"></el-option>
					<!-- <el-option label="模型部署" value="2" v-if="$isReinforce"></el-option> -->
					<el-option label="模型测试" value="3" v-if="!$isReinforce"></el-option>
				</el-select>
			</div>
		</div>

		<div class="table-data">
			<el-table :data="tableData">
				<el-table-column prop="name" label="名称" align="center">
					<template slot-scope="{ row }">
						<el-popover placement="right-start" width="320" trigger="hover">
							<row-data :row="row" />
							<span slot="reference">{{ row.name }}</span>
						</el-popover>
					</template>
				</el-table-column>
				<el-table-column prop="resource.start_time" label="启动时间" align="center" />
				<!-- <el-table-column prop="update_time" label="资源组" /> -->
				<el-table-column prop="update_time" label="运行时长" align="center">
					<template slot-scope="{ row }">
						{{ countRanTime(row.resource.start_time) }}
					</template>
				</el-table-column>

				<!-- <el-table-column prop="update_time" label="环境" /> -->
				<el-table-column prop="status" label="状态" align="center">
					<template slot-scope="{ row }">
						<span :class="['alick-list-status', row.status]">
							<img v-if="row.status === 'failed'" src="~@/assets/img/fail.png" alt="" />
							<span v-else>● </span>
							<span>{{ statusMap[row.status] }}</span>
						</span>
					</template>
				</el-table-column>
				<el-table-column prop="update_time" label="操作" align="center">
					<template slot-scope="{ row }">
						<el-button type="text" @click="goDetail(row)">详情</el-button>
						<el-button type="text" @click="monitoring(row)" :disabled="row.status != 'running'">
							<img src="~@/assets/img/monitoring.png" alt="" />监控
						</el-button>
						<el-button type="text" @click="stop(row)"> <img src="~@/assets/img/stop.png" alt="" />停止</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>

		<div class="pagination-box" v-if="Pagedata.total > Pagedata.size">
			<el-pagination
				background
				class="pagination"
				layout="total, prev, pager, next, jumper"
				:page-size="Pagedata.size"
				:current-page.sync="Pagedata.current"
				@current-change="handleCurrentChange"
				:total="Pagedata.total"
			>
			</el-pagination>
		</div>
		<drawer-log ref="drawerLog" :row="rowData" />
	</v-layout>
</template>

<script>
import Vue from "vue";
import { getGameExperimentMonitor, stopGameExperiment } from "@/api/gameExperiment";
import { getGameTaskVersionsMonitor, stopGameTaskVersion } from "@/api/gameTask";
import { getGameSimulationMonitor, stopGameSimulation } from "@/api/gameSimulation";
import { getExperimentMonitor, stopExperiment } from "@/api/notebook";
import { getTaskVersionsMonitor, stopTaskVersion } from "@/api/task";
import { getDeploysMonitor, stopServing } from "@/api/deploy";
// import { getAllResource, networkUsageCurrent } from '@/api/dashboard'
import { getAllResource, nodeGpuAllocation } from "@/api/dashboard";
import { getCookie } from "@/utils/tool";
import percentage from "./module/percentage";
import drawerLog from "./module/drawer-log";

export default {
	name: "index",
	data() {
		return {
			showThisActive: "0",
			tableData: [],
			rowData: [],
			cpuRes: {},
			memRes: {},
			gpuRes: {},
			diskRes: {},
			gpuLeft: null,
			Pagedata: {
				current: 1,
				size: 10,
				total: 0,
			},
		};
	},
	components: {
		percentage,
		drawerLog,
	},
	methods: {
		applyResource() {},
		parseGpuByType(data) {
			let res = {};
			if (data == null || data.length === 0) {
				return null;
			}
			for (let nodeGpu of data) {
				let gpu = nodeGpu["gpu"];
				if (gpu === "-") {
					continue;
				}
				if (gpu in res) {
					res[gpu] = res[gpu] + nodeGpu.left;
				} else {
					res[gpu] = nodeGpu.left;
				}
			}
			return res;
		},
		async getCakeData() {
			let resCpu = await getAllResource({ resourceType: "cpu" });
			let resMem = await getAllResource({ resourceType: "mem" });
			let resGpu = await getAllResource({ resourceType: "gpu" });
			let resDisk = await getAllResource({ resourceType: "disk" });
			let resNodeGpu = await nodeGpuAllocation();
			console.log("resNodeGpu", resNodeGpu);
			this.gpuLeft = this.parseGpuByType(resNodeGpu.data);

			this.cpuRes = resCpu.data;
			resCpu.data.color = "#F0CB55";
			resCpu.data.underpainting = "rgba(35, 35, 37, .75)";

			this.memRes = resMem.data;
			resMem.data.color = "#439566";
			resMem.data.underpainting = "rgba(35, 35, 37, .75)";

			this.gpuRes = resGpu.data;
			this.gpuRes = resGpu.data;
			resGpu.data.color = "#36B4DA";
			resGpu.data.underpainting = "rgba(35, 35, 37, .75)";

			this.diskRes = resDisk.data;
			resDisk.data.color = "#2E79F6";
			resDisk.data.underpainting = "rgba(35, 35, 37, .5)";
		},
		async getExperiment() {
			let res = null;
			if (this.$isReinforce) {
				res = await getGameExperimentMonitor({ ...this.Pagedata });
			} else {
				res = await getExperimentMonitor({ ...this.Pagedata });
			}

			this.tableData = res.data.list;
			this.Pagedata.total = res.data.total;
		},
		async getTaskVersions() {
			let res = null;
			if (this.$isReinforce) {
				res = await getGameTaskVersionsMonitor({ type: 1, ...this.Pagedata });
			} else {
				res = await getTaskVersionsMonitor({ type: 1, ...this.Pagedata });
			}

			this.tableData = res.data.list;
			this.Pagedata.total = res.data.total;
		},
		async getDeploys() {
			let res = null;
			if (this.$isReinforce) {
				res = await getGameTaskVersionsMonitor({ type: 2, ...this.Pagedata });
			} else {
				res = await getDeploysMonitor({ type: 2, ...this.Pagedata });
			}

			this.tableData = res.data.list;
			this.Pagedata.total = res.data.total;
		},
		async getSimulationTask() {
			let res = await getGameSimulationMonitor({ type: 1, ...this.Pagedata });

			this.tableData = res.data.list;
			for (let i = 0; i < this.tableData.length; i++) {
				this.tableData[i].name = this.tableData[i].deploy_name;
			}
			this.Pagedata.total = res.data.total;
		},
		getData() {
			// this.Pagedata.current = 1
			if (this.showThisActive == 0) {
				this.getExperiment();
			}
			if (this.showThisActive == 1) {
				this.getTaskVersions();
			}
			if (this.showThisActive == 2) {
				this.getDeploys();
			}
			if (this.showThisActive == 3) {
				this.getSimulationTask();
			}
			this.getCakeData();
		},
		monitoringOver(type) {
			let thisType = { ...this[type] };
			thisType.tempColor = thisType.color;
			thisType.tempUnderpainting = thisType.underpainting;
			thisType.color = "#FFF";
			thisType.underpainting = "rgba(255, 255, 255, .2)";
			this[type] = {};
			setTimeout(() => {
				this[type] = thisType;
			});
		},
		monitoringOut(type) {
			let thisType = { ...this[type] };
			thisType.color = thisType.tempColor;
			thisType.underpainting = thisType.tempUnderpainting;
			this[type] = {};
			setTimeout(() => {
				this[type] = thisType;
			});
		},
		goDetail(row) {
			let path;

			if (this.$isReinforce) {
				switch (this.showThisActive) {
					case "0":
						path = "gameExperiment";
						break;
					case "1":
						path = "gameTask";
						break;
					case "2":
						path = "modelTestt";
						break;
				}
			} else {
				switch (this.showThisActive) {
					case "0":
						path = "notebook";
						break;
					case "1":
						path = "task";
						break;
					case "3":
						path = "modelTestt";
						break;
				}
			}

			this.$router.push(`/${path}/code?id=${row.id}`);
		},
		monitoring(row) {
			this.rowData = row;
			this.rowData.active = this.showThisActive;
			this.$refs.drawerLog.shwoDrawer = true;
		},
		async stop({ id }) {
			//console.log(id)
			if (this.showThisActive == 0) {
				if (this.$isReinforce) {
					await stopGameExperiment({ id });
				} else {
					await stopExperiment({ id });
				}
			}
			if (this.showThisActive == 1) {
				if (this.$isReinforce) {
					await stopGameTaskVersion({ id });
				} else {
					await stopTaskVersion({ id });
				}
			}
			if (this.showThisActive == 2) {
				if (this.$isReinforce) {
					await stopGameTaskVersion({ id });
				} else {
					await stopServing(id);
				}
			}
			if (this.showThisActive == 3) {
				await stopGameSimulation(id);
			}
			this.getData();
		},
		checkActicve(i) {
			this.showThisActive = i;
			this.Pagedata.current = 1;
			this.getData();
		},
		handleCurrentChange(val) {
			this.Pagedata.current = val;
			this.getData();
		},
	},
	created() {},
	watch: {},
	beforeCreate() {
		//console.log(decodeURIComponent(getCookie('login_ticket')))
		if (decodeURIComponent(getCookie("login_ticket")) == "") {
			this.$router.push({
				path: "/login",
			});
		}
		return;
	},
	mounted() {
		//
		if (!this.$isFirstPage) {
			Vue.prototype.$isFirstPage = true;
		}
		//
		this.getData();
		this.$EventBus.$on("experiment", () => {
			if (this.showThisActive == 0) this.getData();
		});
		this.$EventBus.$on("train", () => {
			if (this.showThisActive == 1 || this.showThisActive == 2) this.getData();
		});
		this.$EventBus.$on("serving", () => {
			if (this.showThisActive == 2) this.getData();
		});
	},
	destroyed() {
		this.$EventBus.$off("experiment");
		this.$EventBus.$off("train");
		this.$EventBus.$off("serving");
	},
};
</script>
<style lang="less" scoped>
.table-data {
	// padding: 0 16px 16px;
	// background: #FFF;
	// border-radius: 0 10px 10px 10px;

	img {
		height: 14px;
		margin-right: 5px;
		float: left;
	}
}

.home-monitoring {
	display: flex;
	width: 100%;
	margin-bottom: 20px;

	li {
		flex: 1;
		margin: 0 8px;
		height: 260px;
		background: #fff;
		border-radius: 10px;
		cursor: pointer;
		transition: all 0.3s;
		position: relative;
		display: flex;
		flex-direction: column;
		align-items: center;
		display: flex;
		justify-content: center;
		align-items: center;
		padding-top: 30px;
		box-sizing: border-box;

		&:first-child {
			margin-left: 0;
		}

		&:last-child {
			margin-right: 0;
		}

		.monitoring-layer {
			position: absolute;
			left: 0;
			top: 0;
			width: 100%;
			height: 100%;
			z-index: 2;
		}

		.txt {
			position: absolute;
			top: 20px;
			left: 25px;
			color: #a4adcd;

			.name {
				font-size: 18px;
			}

			.msg {
				font-size: 14px;
				margin-top: 15px;

				span {
					font-size: 16px;
				}
			}
		}

		&:hover {
			background: #2a2e46 !important;
		}
	}

	.cpu {
		span {
			color: #f0cb55;
		}
	}

	.vgpu {
		span {
			color: #439566;
		}
	}

	.ram {
		span {
			color: #2e79f6;
		}
	}

	.gpu {
		span {
			color: #36b4da;
		}
	}
}
</style>
